<template>
  <el-drawer
    title="编辑题目"
    :append-to-body="true"
    :wrapperClosable="false"
    size="1300px"
    :visible="show"
    @close="handleClose"
  >
    <div class="container_compontent">
      <div class="">
        <el-form
          @submit.native.prevent
          ref="form"
          :model="form"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="题型" prop="type">
            <el-select
              @change="changeTopicType"
              filterable
              v-model.number="form.type"
              placeholder="请选择题型"
            >
              <el-option
                v-for="item in topicType"
                :key="item.label"
                :label="item.value"
                :value="item.label"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="难度" prop="difficulty">
            <el-select
              filterable
              v-model.number="form.difficulty"
              placeholder="请选择难度"
            >
              <el-option
                v-for="item in topicDifficulty"
                :key="item.label"
                :label="item.value"
                :value="item.label"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="题干" prop="question">
            <el-input
              type="textarea"
              id="textarea"
              v-model="form.question"
              placeholder="请输入题干"
              @blur="campaignNameBlur"
              :autosize="{ minRows: 3, maxRows: 10 }"
            />
            <div class="" v-if="form.type == 'filling'">
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-plus"
                plain
                @click="handleAddBlank"
              >插入填空符
              </el-button>
              <span class="ml10">*填空符由英文括号以及三个下划线组成,例: ___</span>
            </div>
          </el-form-item>
          <div class="table_content" v-if="allTypes.includes(form.type)">
            <div class="label">
              <span>*</span>{{ form.type == 'filling' ? '填空项' : '选项' }}
            </div>
            <div class="main">
              <el-table
                :data="form.ccTopicOptionList"
                ref="multipleTable"
                style="width: 1154px; margin-bottom: 22px"
                :header-cell-style="{ background: '#f4f3f9', color: '#606266' }"
                class="drow_table"
                row-key="id"
              >
                <!--  选择题选择正确选项      -->
                <el-table-column width="60px" align="center" v-if="choiceTypes.includes(form.type)">
                  <template slot-scope="scope">
                    <el-checkbox @change="changeIstrue(scope.row.optionId)" class="selected_box"
                                 v-model="scope.row.isTrue"
                    ></el-checkbox>
                  </template>
                </el-table-column>
                <!--  拖拽排序      -->
                <el-table-column prop="sort" label="拖拽排序" width="120px" align="center">
                  <el-button
                    class="move"
                    icon="el-icon-d-caret"
                    circle
                  ></el-button>
                </el-table-column>
                <!--  填空题      -->
                <el-table-column
                  width="120px"
                  prop="optionIndexStr"
                  v-if="form.type === 'filling'"
                >
                  <template slot-scope="scope">
                    <span>填空{{ scope.$index + 1 }}答案</span>
                  </template>
                </el-table-column>
                <el-table-column>
                  <template slot="header" v-if="choiceTypes.includes(form.type)">
                    <span>勾选设置正确答案</span>
                  </template>
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="`ccTopicOptionList.${scope.$index}.value`"
                      :rules="rules.value"
                      style="margin: 0"
                      label-width="0"
                    >
                      <el-input
                        v-model="scope.row.value"
                        placeholder="请输入选项内容"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column width="200px" align="right">
                  <template slot="header">
                    <el-button
                      type="primary"
                      icon="el-icon-plus"
                      @click="addOption"
                      size="mini"
                    >添加选项
                    </el-button>
                  </template>
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="danger"
                      icon="el-icon-delete"
                      @click="deleteOption(scope.$index)"
                    >删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
          <!--判断题区块 -->
          <div v-if="form.type == 'judgement'">
            <el-form-item label="答案" prop="right">
              <el-radio-group v-removeAriaHidden v-model="form.right" ref="radioGroup">
                <el-radio :label="'正确'">正确</el-radio>
                <el-radio :label="'错误'">错误</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <el-form-item v-if="['QA'].includes(form.type)" label="答案" prop="answer">
            <el-input
              v-model="form.answer"
              type="textarea"
              placeholder="请输入答案"
              :autosize="{ minRows: 3, maxRows: 6 }"
            />
          </el-form-item>
          <el-form-item label="解析" prop="resolve">
            <el-input
              v-model="form.resolve"
              type="textarea"
              placeholder="请输入内容"
              :autosize="{ minRows: 3, maxRows: 6 }"
            />
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="bottom_btns">
      <el-button @click="handleClose">取消</el-button>
      <el-button @click="handleSure" type="primary">
        确定
      </el-button>
    </div>
  </el-drawer>
</template>

<script>
import { v4 as uuidv4 } from 'uuid'
import Sortable from 'sortablejs'

export default {
  name: 'editTopicDrawer',
  props: {
    show: {
      type: Boolean,
      default: false
    },
    topicItem: {
      type: [Object],
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      cursorPosition: 0,
      choiceTypes: ['choice', 'multi_choice'],
      allTypes: ['choice', 'multi_choice', 'filling'],
      topicType: [
        {
          label: 'choice',
          value: '单选题'
        },
        {
          label: 'multi_choice',
          value: '多选题'
        },
        {
          label: 'judgement',
          value: '判断题'
        },
        {
          label: 'filling',
          value: '填空题'
        },
        {
          label: 'QA',
          value: '简答题'
        }
      ],
      rules: {
        value: { required: true, message: '请输入选项内容' },
        type: { required: true, message: '请选择试题类型' },
        difficulty: { required: true, message: '请选择难度' },
        question: { required: true, message: '请输入题干' },
        right: { required: true, message: '请选择正确答案' }
      },
      topicDifficulty: [
        {
          label: '简单',
          value: '简单'
        },
        {
          label: '中等',
          value: '中等'
        },
        {
          label: '困难',
          value: '困难'
        },
        {
          label: '不限难度',
          value: '不限难度'
        }
      ],
      labelList: this.$store.getters.EN,
      form: {
        right: '正确',
        answer: '',
        ccTopicOptionList:[]
      }
    }
  },
  watch: {
    show(val) {
      if (val) {

        if (this.choiceTypes.includes(this.topicItem.type)) {
          let arr = []
          for (const option of this.topicItem.options) {
            let obj = {
              optionId: uuidv4().replace(/-/g, ''),
              value: option,
              label: option.slice(0, 1),
              isTrue: false
            }
            if (this.topicItem.answer.includes(obj.label)) {
              obj.isTrue = true
            }
            arr.push(obj)
          }
          this.topicItem.ccTopicOptionList = arr
        }
        if (this.topicItem.type == 'filling') {
          let content = typeof this.topicItem.answer === 'string' ? [this.topicItem.answer] : this.topicItem.answer
          let arr = []
          for (const contentElement of content) {
            let obj = {
              optionId: uuidv4().replace(/-/g, ''),
              value: contentElement,
              label: 'filling',
              isTrue: false
            }
            arr.push(obj)
          }
          this.topicItem.ccTopicOptionList = arr
        }
        if (this.topicItem.type == 'judgement') {
          console.log(this.topicItem.answer)
          this.topicItem.right = this.topicItem.answer
        } else {
          this.topicItem.right = '错误'
        }
        this.form = {
          ...this.topicItem
        }
      }
    },
    'form.type': {
      handler(val) {
        if (this.choiceTypes.includes(val)) {
          this.$nextTick(() => {
            this.drag()
          })
        }
      },
      deep: true
    }
  },
  methods: {
    changeTopicType() {
      if (this.choiceTypes.includes(this.form.type)) {
        let arr = []
        for (let i = 0; i < 4; i++) {
          arr.push({
            optionId: uuidv4().replace(/-/g, ''),
            value: '',
            label: this.labelList[i],
            isTrue: false
          })
        }
        this.form.ccTopicOptionList = arr
      } else {
        this.form.ccTopicOptionList = []
      }
    },
    changeIstrue(id) {
      if (this.form.type == 'choice') {
        for (const ccTopicOptionListElement of this.form.ccTopicOptionList) {
          ccTopicOptionListElement.isTrue = id == ccTopicOptionListElement.optionId
        }
      }
    },
    handleAddBlank() {
      let num = this.cursorPosition - 0
      if (num > 0) {
        //插入到指定光标处
        let left = this.form.question.slice(0, num)
        let right = this.form.question.slice(num)
        this.form.question = left + '___' + right
        this.cursorPosition = num + 3
      } else {
        //没有指定插入直接添加到最后
        this.cursorPosition += 3
        this.form.question += '___'
      }
    },
    deleteOption(index) {
      this.form.ccTopicOptionList.splice(index, 1)
    },
    addOption() {
      if (this.choiceTypes.includes(this.form.type)) {
        let obj = {
          optionId: uuidv4().replace(/-/g, ''),
          value: '',
          label: 'add',
          isTrue: false
        }
        this.form.ccTopicOptionList.push(obj)
      } else {
        let blankMatches = this.form.question.match(/___/g)
        const blankCount = blankMatches ? blankMatches.length : 0
        const optionCount = this.form.ccTopicOptionList.length
        if (!blankMatches) {
          this.$modal.msgWarning('请先设置填空符!')
          return
        }
        if (optionCount >= blankCount) {
          this.$modal.msgWarning('选项数量不能大于填空数量!')
          return
        }
        let obj = {
          optionId: uuidv4().replace(/-/g, ''),
          value: '',
          label: 'add',
          isTrue: false
        }
        this.form.ccTopicOptionList.push(obj)
      }
    },
    campaignNameBlur(e) {
      this.cursorPosition = e.srcElement.selectionStart
    },
    handleClose() {
      this.$emit('update:show', false)
    },
    handleSure() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.choiceTypes.includes(this.form.type)) {
            if (this.form.ccTopicOptionList.length < 2) {
              this.$modal.msgWarning('选项不能少于两个')
              return
            }
            if (this.form.ccTopicOptionList.filter((item) => item.isTrue).length === 0) {
              this.$modal.msgWarning('请勾选正确答案')
              return
            }
            // 校验 optionValue 不能重复（优化后）
            const optionValues = this.form.ccTopicOptionList.map(item => item.value)
            const uniqueValues = new Set(optionValues)
            if (uniqueValues.size !== optionValues.length) {
              this.$modal.msgWarning('识别到选项内容有重复，请检查后重新输入')
              return
            }
            if (this.form.type == 'multi_choice' && this.form.ccTopicOptionList.filter((item) => item.isTrue).length < 2) {
              this.$modal.msgWarning('多选题答案至少为2个')
              return
            }
          }
          if (this.form.type == 'filling') {
            const blankMatches = this.form.question.match(/___/g)
            const blankCount = blankMatches ? blankMatches.length : 0
            const optionCount = this.form.ccTopicOptionList.length
            if (!blankMatches) {
              this.$modal.msgWarning('请先设置填空符!')
              return
            }
            if (optionCount != blankCount) {
              this.$modal.msgWarning('选项必须与填空数一致')
              return
            }
            this.form.ccTopicOptionList.forEach((option) => {
              option.trueOption = true
            })
          }
          if (this.allTypes.includes(this.form.type)) {
            let trueAnswer = []
            let fillingAnswer = []
            for (const option of this.form.ccTopicOptionList) {
              if (option.isTrue) {
                trueAnswer.push(option.value.slice(0, 1))
              }
              fillingAnswer.push(option.value)
            }
            this.form.answer = trueAnswer.length == 1 ? trueAnswer[0] : JSON.stringify(trueAnswer)
            this.form.options = fillingAnswer
            if (this.form.type == 'filling') {
              this.form.answer = fillingAnswer
            }
          }
          if (this.form.type == 'judgement') {
            this.form.answer = this.form.right
          }
          this.$emit('updateTopic', this.form)
          this.handleClose()
        }else {
          this.$modal.msgWarning('请按规范填写标红文本框内容')
        }
      })
    },
    drag() {
      const el = document.querySelectorAll('.drow_table .el-table__body-wrapper > table > tbody')[0]
      Sortable.create(el, {
        handle: '.move', // 拖拽手柄
        disabled: false, // 拖拽不可用? false 启用
        ghostClass: 'sortable_ghost', //拖拽样式
        animation: 150, // 拖拽延时，效果更好看
        onEnd: (e) => {
          console.log(e.newIndex, e.oldIndex)
          // 拖拽结束时的触发
          let arr = JSON.parse(JSON.stringify(this.form.ccTopicOptionList)) // 获取表数据
          arr.splice(e.newIndex, 0, arr.splice(e.oldIndex, 1)[0]) // 数据处理
          this.$nextTick(() => {
            this.form.ccTopicOptionList = arr
          })
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.container_compontent {
  width: 100%;
  border-top: 1px solid #EBEBEB;
  padding: 14px 24px;
  box-sizing: border-box;
  height: calc(100vh - 144px);
  overflow: auto;

  .table_content {
    display: flex;

    .label {
      font-size: 14px;
      color: #606266;
      width: 100px;
      padding: 0 12px 0 0;
      box-sizing: border-box;
      text-align: right;
      font-weight: bold;

      span {
        color: #f67878;
        margin-right: 4px
      }
    }

    .main {
      flex: 1;
    }
  }
}

.bottom_btns {
  width: 100%;
  padding: 10px 24px;
  box-sizing: border-box;
  display: flex;
  justify-content: flex-end;
}

.sortable_ghost {
  background: transparent;
}
</style>

